//
//  ViewController.m
//  avatar
//
//  Created by hoho on 14-11-17.
//  Copyright (c) 2014年 thinkcart.net. All rights reserved.
//

#import "ViewController.h"
#import "PSTAlertController.h"
#import "DZImageEditingController.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIView+Toast.h"

@interface ViewController () <UIImagePickerControllerDelegate, DZImageEditingControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *avatarImageView;

@property (strong, nonatomic) UIImageView *overlayImageView;
@property (nonatomic) CGRect frameRect;

@property (strong, nonatomic) NSString *documentsDirectory;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    self.documentsDirectory = [paths objectAtIndex:0];
    
    //检查首选项中是否保存有头像信息，有则设置之
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    NSString *avatarImage = [userdefaults objectForKey:@"avatar"];
    if(avatarImage){
        NSString *avatarPath = [self.documentsDirectory stringByAppendingPathComponent:avatarImage];
        if([[NSFileManager defaultManager] fileExistsAtPath:avatarPath]){
            UIImage *image = [UIImage imageWithContentsOfFile:avatarPath];
            [self.avatarImageView setImage:image];
        }
    }
    
    //给头像图片设置点击事件
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self
                                         action:@selector(getImage)];
    [singleTap setNumberOfTapsRequired:1];
    self.avatarImageView.userInteractionEnabled = YES;
    [self.avatarImageView addGestureRecognizer:singleTap];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - private

- (UIImageView *)createOverlayImageViewWithImage:(UIImage *)image {
    CGFloat newX = [UIScreen mainScreen].bounds.size.width / 2 - image.size.width / 2;
    CGFloat newY = [UIScreen mainScreen].bounds.size.height / 2 - image.size.height / 2;
    self.frameRect = CGRectMake(newX, newY, image.size.width, image.size.height);
    return [[UIImageView alloc] initWithFrame:self.frameRect];
}

- (void)imagePicker :(NSInteger)type {
    UIImagePickerController *pickerController = [UIImagePickerController new];
    if(type == 1){
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else{
            PSTAlertController *alertController = [PSTAlertController alertWithTitle:@"当前没有可用的照像机" message:nil];
            [alertController addAction:[PSTAlertAction actionWithTitle:@"确定" handler:NULL]];
            [alertController showWithSender:nil controller:self animated:YES completion:NULL];
            return;
        }
    }else{
        pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    pickerController.delegate = self;
    [self presentViewController:pickerController
                       animated:YES
                     completion:nil];
}

#pragma mark action

- (void)getImage {
    
    if(self.overlayImageView == nil){
        UIImage *overlayImage = [UIImage imageNamed:@"overlay200"];
        self.overlayImageView = [self createOverlayImageViewWithImage:overlayImage];
        self.overlayImageView.image = overlayImage;
    }
    
    PSTAlertController *sheetController = [PSTAlertController actionSheetWithTitle:@"更换头像"];
    [sheetController addAction:[PSTAlertAction actionWithTitle:@"从相册中选取" handler:^(PSTAlertAction *action) {
        [self imagePicker:0];
    }]];
    [sheetController addAction:[PSTAlertAction actionWithTitle:@"用照相机拍摄" handler:^(PSTAlertAction *action){
        [self imagePicker:1];
    }]];
    [sheetController addAction:[PSTAlertAction actionWithTitle:@"取消" style:PSTAlertActionStyleCancel handler:NULL]];
    [sheetController showWithSender:[NSValue valueWithCGRect:CGRectMake(100.f, 100.f, 1.f, 1.f)] controller:self animated:YES completion:^{
    }];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [self dismissViewControllerAnimated:NO completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        DZImageEditingController *editingViewController = [DZImageEditingController new];
        editingViewController.image = image;
        editingViewController.overlayView = self.overlayImageView;
        editingViewController.cropRect = self.frameRect;
        editingViewController.delegate = self;
        
        [self presentViewController:editingViewController
                           animated:YES
                         completion:nil];
    }];
}

#pragma mark - DZImageEditingControllerDelegate

- (void)imageEditingControllerDidCancel:(DZImageEditingController *)editingController {
    [editingController dismissViewControllerAnimated:YES
                                          completion:nil];
}

- (void)imageEditingController:(DZImageEditingController *)editingController
     didFinishEditingWithImage:(UIImage *)editedImage {

    //结束编辑
    [editingController dismissViewControllerAnimated:YES
                                          completion:nil];
    
    //设置新头像
    [self.avatarImageView setImage:editedImage];
    
    //图片保存至documents diretory
    NSData *imageData = UIImageJPEGRepresentation(editedImage, 0.5);//第二个参数是压缩系数
    //NSData *imageData = UIImagePNGRepresentation(editedImage); //这是png类型的
    NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:@"avatar.jpg"];
    [imageData writeToFile:destinationPath atomically:YES];
    
    //首选项保存头像信息
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //模拟器中，每次启动获取到的documents diretory路径都不一样的，不知道为什么这样
    //所以保存了这个路径，下次启动取出来，但已经不正确了
    //[userDefaults setValue:destinationPath forKey:@"avatar"];
    [userDefaults setObject:@"avatar.jpg" forKey:@"avatar"];//可以用UID区分不同用户帐号
    
    //上传头像图片至服务器
    [self.view makeToastActivity];//显示“正在上传中”
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"foo": @"bar"};
    [manager POST:@"http://localhost/test/upload.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"image" fileName:@"avatar.jpg" mimeType:@"image/jpg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view hideToastActivity];//隐藏“正在上传中”
        [self.view makeToast:@"上传成功！"];
        /*
        NSDictionary *jsonDict = (NSDictionary *) responseObject;
        NSString *response = [jsonDict objectForKey:@"res"];
        [self.view makeToast:response];
         */
        NSLog(@"Success: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view hideToastActivity];//隐藏“正在上传中”
        [self.view makeToast:@"上传失败！"];
        NSLog(@"Error: %@", error);
    }];
}


@end
